﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using Microsoft.Office.Interop.Excel;
using XRM.Security.WebUI.Helpers;

namespace XRM.Security.WebUI.Models.Report.ReportBuilder
{
    public abstract class ReportBuilderBase : IReportBuilder
    {
        public abstract string TemplateFileName
        {
            get;
        }

        public abstract string Create( CreateReportModel model );

        public static string GetTempFileFolder()
        {
            var folderPath = Utils.GetPhisicalPath( ConfigurationManager.AppSettings["TempFilesFolder"] );
            if ( !Directory.Exists( folderPath ) )
                Directory.CreateDirectory( folderPath );
            return folderPath;
        }

        protected string CreateXlsxDocument( string xmlDoc )
        {
            var templateFolder = Utils.GetPhisicalPath(ConfigurationManager.AppSettings["ReportTemplatesPath"]);
            var reportFileId = Guid.NewGuid().ToString();
            var reportFilePath = Path.Combine( GetTempFileFolder(), String.Format( "{0}{1} ({2:dd.MM.yyyy}).xlsx", reportFileId, TemplateFileName, DateTime.Today ) );
            var excel = new Application();
            var workbook = excel.Workbooks.Open( Path.Combine( templateFolder, String.Format( "{0}.xlsx", TemplateFileName ) ) );
            try
            {
                workbook.SaveCopyAs( reportFilePath );
            }
            catch
            {
                ExitExcel(excel);
                throw;
            }
            workbook.Close();
            
            try
            {
                workbook = excel.Workbooks.Open( reportFilePath );
                XmlMap xmlMap;
                workbook.XmlImportXml( xmlDoc, out xmlMap );
                workbook.Close(true);
            }
            finally
            {
                ExitExcel(excel);
            }
            return reportFileId;
        }

        private static void ExitExcel( Application excel )
        {
            excel.Application.Quit();
            excel.Quit();
            foreach ( var process in Process.GetProcessesByName( "EXCEL" ) )
            {
                process.Kill();
            }
        }
    }
}